<template>
  <el-container class="h-100 p-3" id="user-statistics">
    <el-main class="p-0">
      <el-row>
        <el-row class="seach-text">
          <el-input v-model="searchText" style="width:200px" placeholder="输入姓名/手机查询"></el-input>
          <el-button icon="el-icon-search" @click="searchPerson()"></el-button>
          <el-button style="margin-right:5px;" :class="mapButton" @click="recoveryMap()">恢复全图</el-button>
        </el-row>
        <el-row style="position:absolute;z-index:900;width:100%;top:65px;">
          <el-button
            v-show="isShow"
            style="margin-right:5px;"
            :class="mapButton"
            @click="gotoProvince()"
          >{{backLevel}}</el-button>
        </el-row>
      </el-row>
      <InitMap
        ref="map"
        height="100%"
        backgroundColor="white"
        @getChoiceGraphics="gClick"
        @dbClick="dbClick"
      />
    </el-main>
    <el-aside width="500px" class="ml-3 text-center">
      <ProofProgress :busData="busData" @sendObj="setData"/>
    </el-aside>
    <el-dialog title="人员信息" :visible.sync="dialogFormVisible" width="40%">
      <el-row>
        <el-col :span="8">
          <img
            style="height:200px;width: 90%;"
            :src="currentSelectPerson.avatar || 'static/man.png'"
          >
        </el-col>
        <el-col :span="16">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{currentSelectPerson.name}}</span>
              <span>{{currentSelectPerson.sex=='1'?'（男）':'（女）'}}</span>
            </div>
            <div class="text item">{{'手机号码: '+ currentSelectPerson.mobile}}</div>
            <div class="text item">{{'作业单位: '+ currentSelectPerson.userCompany}}</div>
            <div class="text item">{{'负责区域: '+currentSelectPerson.areaName}}</div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </el-container>
</template>
<script>
import InitMap from "../map/InitMap";
import axios from "axios";
import ProofProgress from "./ProofProgress"; // 各地市举证进度
import config from "@/config";
const tempLayerId = "personMarker";
const proviceName = "610000";
const tempClusterLayerId = "cluster-layer";
const defaultScal = 4000000;
const defaultFil = 0.7;

export default {
  name: "userstatistics",
  title: "人员统计",
  components: { InitMap, ProofProgress },
  data() {
    return {
      isLoadComplate: false,
      searchText: "",
      currentMarker: [],
      dialogFormVisible: false,
      currentSelectPerson: {
        name: "",
        sex: 1,
        mobile: "",
        userCompany: "",
        cityName: "",
        areaName: ""
      },
      currentCityId: "",
      currentProvinceId: "",
      markers: {},
      pointMarker: null,
      backLevel: "返回省级",
      mapButton: "mapButton",
      currentCenter: null,
      currentAreaId: "",
      busData: {
        isProvince: true,
        regionId: ""
      },
      isShow: true
    };
  },
  methods: {
    setData(obj) {
      this.busData = JSON.parse(JSON.stringify(obj));
      let cityId = this.busData.regionId;
      let isProvice = this.busData.isProvince;
      let parmater = {};
      if (!isProvice) {
        this.currentCityId = cityId;
        parmater = { cityId: cityId };
      } else {
        parmater = { cityId: proviceName };
      }

      this.cityChanged(parmater);
    },
    searchPerson() {
      let url = "";
      let _this = this;
      if (this.searchText == "") {
        this.$message("请输入需要查询的信息");
        return;
      }
      this.$get(_this.$api.getOnlineOutdoorUser, {
        name: _this.searchText,
        type: _this.busData.selectType
      }).then(res => {
        if (res.data.code === "200") {
          var result = res.data.data;
          let _this = this;
          if (result.length == 0) {
            this.$message("当前人没在线");
          } else {
            var ll = result[0];
            ll.isPerson = 1;
            this.addLocationMarker(ll.gpsX, ll.gpsY, ll);
          }
        }
      });
    },
    addLocationMarker(lng, lat, personAttr) {
      if (this.currentMarker.length > 0) {
        this.currentMarker.forEach(item => {
          this.$refs.map.removeTempLayersGraphic(tempLayerId, item);
        });
      }
      this.currentMarker = [];
      if (this.isLoadComplate) {
        this.$refs.map
          .addMarkerToLayer(
            lng,
            lat,
            "static/person_select.png",
            0,
            tempLayerId,
            { width: "40px", height: "40px", attributes: personAttr }
          )
          .then(gc => {
            this.currentMarker.push(gc);
            this.$refs.map.mapCenterAt([lng, lat], 8, 500000);
          });
      } else {
        this.$message({
          showClose: true,
          message: "初始化未完成，不能进行查询",
          type: "warning"
        });
      }
    },
    gClick(gc) {
      if (gc.selectGraphics != null) {
        let _this = this;
        gc.selectGraphics.forEach(item => {
          if (item.graphic.attributes) {
            if (item.graphic.attributes) {
              if (item.graphic.attributes.isPerson == 1) {
                _this.dialogFormVisible = true;
                _this.currentSelectPerson.avatar =
                  item.graphic.attributes.avatar;
                _this.currentSelectPerson.name =
                  item.graphic.attributes.appName;
                _this.currentSelectPerson.sex = item.graphic.attributes.appSex;
                _this.currentSelectPerson.mobile =
                  item.graphic.attributes.appMobile;
                _this.currentSelectPerson.userCompany =
                  item.graphic.attributes.appCompany || "";
                _this.currentSelectPerson.cityName =
                  item.graphic.attributes.cityName;
                _this.currentSelectPerson.areaName =
                  item.graphic.attributes.areaName;
                _this.currentSelectPerson.account =
                  item.graphic.attributes.appAccount;
                if (_this.pointMarker == item.graphic) {
                  return;
                }
                if (_this.pointMarker != null) {
                  _this.$refs.map.changeMarkerSymbol(
                    _this.pointMarker,
                    "static/person_normal.png",
                    { width: "20px", height: "20px" }
                  );
                }
                this.$refs.map.changeMarkerSymbol(
                  item.graphic,
                  "static/person_select.png",
                  { width: "40px", height: "40px" }
                );
                this.pointMarker = item.graphic;
              }
            }
          }
        });
      }
    },
    dbClick(gc) {
      if (gc.selectGraphics != null) {
        let _this = this;
        let person = [];
        gc.selectGraphics.forEach(item => {
          let att = item.graphic.attributes;
          if (att) {
            if (_this.currentCityId != "") {
              return;
            }
            if (att.cityId) {
              _this.cityChanged({ cityId: att.cityId });
              _this.currentCityId = att.cityId;
              _this.busData.regionId = att.cityId;
              _this.busData.isProvince = false;
            }
          }
        });
      }
    },
    gotoProvince() {
      if (this.currentCityId == "") {
        return;
      }
      let _this = this;
      if (this.currentAreaId != "") {
        this.currentAreaId = "";
        this.cityChanged({
          cityId: _this.currentCityId
        });
      } else {
        this.cityChanged({
          cityId: proviceName
        });
        this.currentCityId = "";
      }
      this.busData.regionId = "";
      this.busData.isProvince = true;
    },
    recoveryMap() {
      if (this.currentCenter.length == 0) {
        this.currentCenter = this.$commonUtils.provinceCenter;
      }
      this.$refs.map.mapCenterAt(this.currentCenter, 8, this.currentScal);
    },
    getOnlinePersons(proviceId, cityId) {
      let url = "";
      if (proviceId == cityId) {
        cityId = null;
      }
      let _this = this;
      this.$get(_this.$api.getOnlineOutdoorUser, {
        cityId: cityId,
        type: _this.busData.selectType
      }).then(res => {
        if (res.data.code === "200") {
          var result = res.data.data;
          this.getOnlinePersonsCluster(result);
        }
      });
    },
    cityChanged(e) {
      this.$refs.map.removeGraphics();
      this.$refs.map.removeAllTempLayersGraphic(tempLayerId);
      this.$refs.map.removeAllTempLayersGraphic(tempClusterLayerId);
      let scal = defaultScal;
      if (e.cityId == proviceName) {
        this.getCityMap(e.cityId, scal, this.$commonUtils.provinceCenter);
      } else {
        this.$commonUtils.cityScal.forEach(sc => {
          if (sc.cityId == e.cityId) {
            scal = sc.cityScal;
          }
        });     
        this.currentScal = scal;
        this.getCityMap(e.cityId, scal);
      }
    },
    getCityMap(name, scal, cPoint) {
      if (
        this.$store.state.user.user.userType == 3 ||
        this.$store.state.user.user.userType == 4
      ) {
        name = this.$store.state.user.user.cityId;
        scal=2000000;
      }
      let url = this.$api.getRegionByCode + "?code=" + name;
      let lables = [];
      let _this = this;
      axios.get(url).then(res => {
        if (res.data.code === "200") {
          // 一下加0.4，2.2为手动试验出来的，不准确可以自己调
          let centerPoinit =
            cPoint == undefined
              ? [res.data.data[0].lnt, res.data.data[0].lat]
              : cPoint;
          this.currentCenter = centerPoinit;
          this.currentScal = scal;
          let colors = [
            [16, 196, 229, defaultFil], // 安康
            [51, 152, 220, defaultFil], // 汉中
            [16, 196, 229, defaultFil], // 汉中
            [51, 152, 220, defaultFil], // 汉中
            [93, 150, 73, defaultFil], // 汉中
            [231, 162, 61, defaultFil], // 汉中
            [16, 196, 229, defaultFil], // 汉中
            [93, 150, 73, defaultFil], // 汉中
            [16, 196, 229, defaultFil], // 汉中
            [51, 152, 220, defaultFil] // 汉中
          ];
          let drawComplate = 0;
          res.data.data[0].child.forEach((element, i) => {
            let paths = [];

            if (this.$store.state.user.user.userType == 4) {
              if (
                element.cityCode.indexOf(this.$store.state.user.user.areaId) < 0
              ) {
                return;
              } else {
                centerPoinit = [element.lnt, element.lat];
                scal = 200000;
                lables.push({
                  point: [element.lnt, element.lat],
                  name: element.name
                });
              }
            } else {
              lables.push({
                point: [element.lnt, element.lat],
                name: element.name
              });
            }
            element.points.forEach(el => {
              let lngLats = el.region.split(",");
              let crings = [];
              lngLats.forEach(ll => {
                let lngLat = ll.split(" ");
                crings.push([lngLat[0], lngLat[1]]);
              });
              paths.push(crings);
            });
            let cor = colors.length > i ? colors[i] : colors[0];
            let eAtt = {
              cityId: element.cityCode.substring(3, element.cityCode.length),
              cityName: element.name
            };
            this.$refs.map
              .addMultiplePolygon(paths, cor, "white", eAtt)
              .then(status2 => {
                if (status2) {
                  drawComplate++;
                  if (drawComplate == lables.length) {
                    this.$refs.map.mapCenterAt(centerPoinit, 8, scal);
                    _this.getOnlinePersons(proviceName, name);
                  }
                }
              });
          });
        } else {
          console.log(res);
        }
      });
    },
    getOnlinePersonsCluster(data) {
      this.$refs.map.removeGraphicsLayer(tempClusterLayerId);
      if (data.length == 0) {
        return;
      }
      data.forEach(d => {
        d.isPerson = 1;
      });

      let options = {
        width: "20px",
        height: "20px",
        lng: "gpsX",
        lat: "gpsY",
        name: "appAccount",
        flareProperty: "appAccount"
      };
      this.$refs.map
        .clusterLayerSingle(
          data,
          "static/person_normal.png",
          tempClusterLayerId,
          options
        )
        .then(gc => {
          //this.$refs.map.mapCenterAt([108.456123, 34.21547], 8, 5000);
        });
    }
  },
  mounted() {
    this.$refs.map.loadWebTileMap().then(status => {
      if (status) {
        let _this = this;
        this.$refs.map.creatGraphicsLayer().then(status1 => {
          if (!status1) {
            return;
          }
          this.getCityMap(
            proviceName,
            defaultScal,
            this.$commonUtils.provinceCenter
          );
        });

        this.$refs.map.creatTempGraphicsLayer(tempLayerId).then(status => {
          this.isLoadComplate = true;
          this.$refs.map.getChoiceGraphics();
          this.$refs.map.hitTestGraphicEvent("double-click", "dbClick");
        });
        if (this.$store.getters.userType == 3) {
          this.busData = {
            isProvince: false,
            regionId: "",
            selectType: "1"
          };
          this.isShow = false;
        } else if (this.$store.getters.userType == 4) {
          this.busData = {
            isProvince: false,
            regionId: "",
            selectType: "1"
          };
          this.isShow = false;
        } else {
          this.busData = {
            isProvince: true,
            regionId: "",
            selectType: "1"
          };
        }
      }
    });
  }
};
</script>
<style lang='scss'>
#user-statistics {
  .seach-text {
    position: absolute;
    z-index: 100;
    width: 100%;
    margin-top: 14px;
  }
  .text {
    font-size: 14px;
  }
  .item {
    margin-bottom: 18px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both;
  }
  .box-card {
    width: 100%;
    height: 200px;
  }
}
</style>